import logging
import logging.handlers
import datetime
import inspect
import os
import colorlog


def get_project_path():
    """ 获取项目根路径 """
    return os.path.split(os.path.split(os.path.realpath(__file__))[0])[0]


class ContextFilter(logging.Filter):
    def filter(self, record):
        frame = inspect.stack()[6]  # Adjust the stack index based on your code structure
        record.filename = os.path.basename(frame.filename)
        record.funcName = frame.function
        record.lineno = frame.lineno
        return True


class LoggerUtil:
    def create_log(self, logger_name='log'):
        self.logger = logging.getLogger(logger_name)
        self.logger.setLevel(logging.DEBUG)

        if not self.logger.handlers:
            self.file_log_path = get_project_path() + '/logs/' + 'log'
            self.handler = logging.handlers.TimedRotatingFileHandler(
                self.file_log_path, when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0))
            self.formatter = logging.Formatter(
                "[%(asctime)s]-[%(filename)s] %(funcName)s line:%(lineno)d [%(levelname)s]: %(message)s", "%Y-%m-%d %H:%M:%S")
            self.handler.setFormatter(self.formatter)
            self.logger.addHandler(self.handler)

            # 控制台输出：
            self.console = logging.StreamHandler()

            # 使用 colorlog 格式化程序
            color_formatter = colorlog.ColoredFormatter(
                "%(log_color)s[%(asctime)s]-[%(filename)s] %(funcName)s line:%(lineno)d [%(levelname)s]: %(message)s",
                datefmt="%Y-%m-%d %H:%M:%S",
                log_colors={
                    'DEBUG': 'cyan',
                    'INFO': 'green',
                    'WARNING': 'yellow',
                    'ERROR': 'red',
                    'CRITICAL': 'bold_red',
                }
            )
            self.console.setFormatter(color_formatter)
            self.logger.addHandler(self.console)

            # 用于对日志记录进行过滤和修改。
            self.logger.addFilter(ContextFilter())  # Add the custom filter
        return self.logger


def write_loging(log_name, log_level='info'):
    logger = LoggerUtil().create_log()
    if log_level == 'debug':
        logger.debug(log_name)
    elif log_level == 'info':
        logger.info(log_name)
    elif log_level == 'warning':
        logger.warning(log_name)
    valid_levels = ['debug', 'info', 'warning']
    if log_level not in valid_levels:
        print("Invalid log_level parameter. Please provide a valid log level.'debug', 'info', 'warning'")
        return


def error_loging(log_name, log_level='error'):
    logger = LoggerUtil().create_log()
    if log_level == 'error':
        logger.error(log_name)
    elif log_level == 'critical':
        logger.critical(log_name)
    valid_levels = ['error', 'critical']
    if log_level not in valid_levels:
        print("Invalid log_level parameter. Please provide a valid log level,'error', 'critical'")
        return


if __name__ == '__main__':
    write_loging('测试222', log_level='debug')
